// ==UserScript==
// @name         电商日清日结表生成
// @namespace    https://gitee.com/vbox007/
// @version      1.0.0.2
// @description  为了让日清日结这种无聊的事变得简单！
// @author       vbox007
// @icon         
// @match        https://zt.hiboos.com/daily/settlement
// @connect      dmall.com
// @grant        GM_xmlhttpRequest
// @require      https://cdn.bootcdn.net/ajax/libs/xlsx/0.16.9/xlsx.full.min.js
// ==/UserScript==

(function () {
    'use strict';
    var $ = function (x) {
        return document.getElementById(x);
    };
    var dmallId, hiboosId, dmallxls, hiboosxls, outtbody, getover, htmlorxls;
    (function () {
        document.head.innerHTML = '<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />\n'
            + '<link rel="shortcut icon" type="image/ico" href="">\n'
            + '<title>电商课日清日结表生成</title>\n'
            + '<style>\n'
            + 'body {text-align:center;}\n'
            + 'div {margin: 0 auto; overflow:auto; text-align:center;}\n'
            + 'table {min-height:25px; line-height:16px; border-collapse:collapse; margin-bottom:0;}\n'
            + 'th {white-space: nowrap; font-size:1px;}\n'
            + 'td {font-size:1px;}\n'
            + '</style>';
    })();//修改页面head
    (function () {
        document.body.innerHTML = '<div id="createsetup" style="width:800px;">\n'
            + '    <table border=1 frame=void rules=none>\n'
            + '        <tbody>\n'
            + '            <tr>\n'
            + '                <td style="width: 215px;font-size: 1vw;">生成哪天的表格：</td>\n'
            + '                <td style="width: 502px;font-size: 1vw;">多点登陆情况：<span id="dmalllogin">读取中……</span></td>\n'
            + '            </tr>\n'
            + '            <tr>\n'
            + '                <td>\n'
            + '                    <input id="createdate" type="date"/>\n'
            + '                </td>\n'
            + '                <td style="font-size: 1vw;">海博登陆情况：<span id="hibooslogin">读取中……</span></td>\n'
            + '            </tr>\n'
            + '            <tr>\n'
            + '                <td colspan=2>\n'
            + '                    <button id="htmlprint" style="width: 100%" disabled="disabled">输出HTML打印版</button>\n'
            + '                </td>\n'
            + '            </tr>\n'
            + '            <tr>\n'
            + '                <td colspan=2>\n'
            + '                    <button id="xlsprint" style="width: 100%" disabled="disabled">输出excel打印版（敬请期待……）</button>\n'
            + '                </td>\n'
            + '            </tr>\n'
            + '        </tbody>\n'
            + '    </table>\n'
            + '</div>\n'
            + '<div id="printpage" style="width: 800px;display:none;">\n'
            + '    <table border=1>\n'
            + '        <thead>\n'
            + '            <tr>\n'
            + '                <th style="width: 112px;">日期时间</th>\n'
            + '                <th style="width: 24px;">班次</th>\n'
            + '                <th style="width: 104px;">订单号</th>\n'
            + '                <th style="width: 64px;">订单<br/>是否出货</th>\n'
            + '                <th style="width: 48px;">取消/退货</th>\n'
            + '                <th style="width: 296px;">商品名称</th>\n'
            + '                <th style="width: 24px;">数量</th>\n'
            + '                <th style="width: 64px;">商品<br/>是否退回</th>\n'
            + '                <th style="width: 80px;">当班防损/<br/>客服签字</th>\n'
            + '            </tr>\n'
            + '        </thead>\n'
            + '        <tbody id="printtbody">\n'
            + '        </tbody>\n'
            + '    </table>\n'
            + '</div>\n'
    })();//页面初始body建立
    (function () {
        var getstrtime = function (difft, c_type, c_one) {
            var nowdate = new Date();
            if (difft) {
                nowdate.setTime(nowdate.getTime() + difft);
            }
            var nowmon = nowdate.getMonth() + 1;
            var strDate = nowdate.getDate();
            if (nowmon >= 1 && nowmon <= 9) {
                nowmon = "0" + nowmon;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var cdate;
            if (c_type == 1) {
                if (c_one) {
                    cdate = '' + nowdate.getFullYear() + nowmon + "01";
                } else {
                    cdate = '' + nowdate.getFullYear() + nowmon + strDate;
                }
            } else if (c_type == 2) {
                cdate = nowdate.getFullYear() + '年' + nowmon + '月' + strDate + '日';
            } else {
                cdate = nowdate.getFullYear() + '-' + nowmon + '-' + strDate;
            }
            return cdate;
        };//获取今天的日期文本
        $("createdate").value = getstrtime();
    })();//给input写入今天的日期
    (function () {
        var loggedin;
        var enbtn = function () {
            if (loggedin == 3) {
                $('htmlprint').removeAttribute("disabled");
                // $('xlsprint').removeAttribute("disabled");
            }
        };
        GM_xmlhttpRequest({
            method: "post",
            url: "https://waybillsmartallot-partner.dmall.com/api/getStoreList",
            data: null,
            headers: {
                "accept": "application/json, text/javascript, */*; q=0.01",
                "accept-language": "zh-CN,zh;q=0.9",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-site"
            },
            onload: function (res) {
                try {
                    var pobj = JSON.parse(res.responseText);
                    dmallId = pobj.data[0].storeId;
                    $('dmalllogin').innerText = '已登陆到 ' + pobj.data[0].storeName;
                    loggedin |= 1;
                    enbtn();
                } catch (error) {
                    $('dmalllogin').innerText = '未检测到登陆状态，请确认登陆后刷新';
                }
            },
            onerror: function (err) {
                $('dmalllogin').innerText = '未检测到登陆状态，请确认登陆后刷新';
            }
        });
        fetch("https://zt.hiboos.com/station/getUserRelated?body=%7B%7D", {
            "headers": {
                "accept": "application/json, text/plain, */*",
                "accept-language": "zh-CN,zh;q=0.9",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin"
            },
            "referrer": "https://zt.hiboos.com/index.html",
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": null,
            "method": "GET",
            "mode": "cors",
            "credentials": "include"
        }).then(res => res.json()).then(pobj => {
            try {
                hiboosId = pobj.result[0].stationId;
                $('hibooslogin').innerText = '已登陆到 ' + pobj.result[0].stationName;
                loggedin |= 2;
                enbtn();
            } catch (e) {
                $('hibooslogin').innerText = '未检测到登陆状态，请确认登陆后刷新';
            };
        });
    })();//获取登陆状态
    var createtbody = function () {
        dmallxls.push.apply(dmallxls, hiboosxls);
        dmallxls.sort(function (a, b) {
            if (a[0] < b[0]) {
                return -1;
            }
            if (a[0] > b[0]) {
                return 1;
            }
            return 0;
        });//按时间排序
        console.log(dmallxls);
        $('createdate').removeAttribute("disabled");
        if (htmlorxls == 1) {
            $('htmlprint').removeAttribute("disabled");
            $('htmlprint').innerText = '输出HTML打印版';
            if (dmallxls.length == 0) {
                $('htmlprint').innerText = '输出HTML打印版（' + $("createdate").value + '无售后单）';
            } else {
                var changerow = function (tbid, crows) {
                    var tbev = $('printtbody');
                    var tcells;
                    tcells = tbev.parentNode.rows[0].cells.length;
                    var tadre = tbev.rows.length - crows;
                    var i = 0;
                    for (i = 0; i < tadre; i++) {
                        tbev.lastChild.remove();
                    }
                    tadre = -tadre;
                    for (i = 0; i < tadre; i++) {
                        var ntr = document.createElement("tr");
                        ntr.innerHTML = new Array(tcells + 1).join('<td></td>');
                        tbev.appendChild(ntr);
                    }
                };//修改表格tbody的行数
                changerow('printtbody', dmallxls.length);
                for (var i = 0; i < dmallxls.length; i++) {
                    $('printtbody').rows[i].cells[0].innerText = dmallxls[i][0];
                    $('printtbody').rows[i].cells[2].innerText = dmallxls[i][1];
                    $('printtbody').rows[i].cells[4].innerText = dmallxls[i][2];
                    $('printtbody').rows[i].cells[5].innerText = dmallxls[i][3];
                    $('printtbody').rows[i].cells[6].innerText = dmallxls[i][4];
                }
                $('createsetup').style.display = 'none';
                $('printpage').style.display = '';
                window.print()
                $('createsetup').style.display = '';
                $('printpage').style.display = 'none';
            }
        } else if (htmlorxls == 2) {
            $('xlsprint').removeAttribute("disabled");
            $('xlsprint').innerText = '输出excel打印版';
        }
        htmlorxls = 0
    };
    var getdmallxls = function () {
        GM_xmlhttpRequest({
            method: "post",
            url: "https://refund-partner.dmall.com/rtnGoods",
            data: 'erpStoreId=["12907"]&startDate=' + $("createdate").value + '&endDate=' + $("createdate").value + '&currentPage=1&pageSize=50',
            headers: {
                "accept": "application/json, text/javascript, */*; q=0.01",
                "accept-language": "zh-CN,zh;q=0.9",
                "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-site",
                "referrer": "https://partner.dmall.com/",
                "referrerPolicy": "strict-origin-when-cross-origin",
                "mode": "cors",
                "credentials": "include"
            },
            onload: function (res) {
                try {
                    var pobj = JSON.parse(res.responseText);
                    dmallxls = [];
                    if (pobj.data.amount == 0) {
                        getover |= 1;
                        if (getover == 3) {
                            createtbody();
                        }
                        return true;
                    }
                    var templist = [];
                    for (var i = 0; i < pobj.data.data.length; i++) {
                        if (pobj.data.data[i].tradeTypeDesc == "O2O订单" && pobj.data.data[i].createName != "自提超时JOB" && pobj.data.data[i].receiveTimeFormatted.substring(0, 10) == $("createdate").value) {
                            var dmallrow = [];
                            dmallrow[0] = pobj.data.data[i].receiveTimeFormatted;
                            dmallrow[1] = pobj.data.data[i].orderId;
                            dmallrow[2] = pobj.data.data[i].refundTypeDesc == "整单退款" ? "整单退款" : "售后退款";
                            dmallrow[3] = pobj.data.data[i].rtnGoodsId;
                            templist[templist.length] = dmallrow;
                        }
                    }
                    if (templist.length == 0) {
                        getover |= 1;
                        if (getover == 3) {
                            createtbody();
                        }
                        return true;
                    }
                    var getwares = function (idrow) {
                        if (idrow >= templist.length) {
                            getover |= 1;
                            if (getover == 3) {
                                createtbody();
                            }
                            return true;
                        }
                        GM_xmlhttpRequest({
                            method: "GET",
                            url: "https://refund-partner.dmall.com/rtnGoods/wares?id=" + templist[idrow][3],
                            headers: {
                                "accept": "application/json, text/javascript, */*; q=0.01",
                                "accept-language": "zh-CN,zh;q=0.9",
                                "sec-fetch-dest": "empty",
                                "sec-fetch-mode": "cors",
                                "sec-fetch-site": "same-site",
                                "referrer": "https://partner.dmall.com/",
                                "referrerPolicy": "strict-origin-when-cross-origin",
                                "mode": "cors",
                                "credentials": "include"
                            },
                            onload: function (res) {
                                var pobj = JSON.parse(res.responseText);
                                for (var i = 0; i < pobj.data.length; i++) {
                                    var dmallrow = [];
                                    for (var j = 0; j < 3; j++) {
                                        dmallrow[j] = templist[idrow][j]
                                    }
                                    dmallrow[3] = pobj.data[i].wareName;
                                    dmallrow[4] = pobj.data[i].returnNum;
                                    dmallxls[dmallxls.length] = dmallrow;
                                }
                                getwares(idrow + 1);
                            }
                        });
                    }
                    getwares(0);
                } catch (err) {
                    console.log(err.message);
                }
            },
            onerror: function (err) {
                console.log(err.message);
            }
        });
    };
    var gethiboosxls = function () {
        fetch("https://zt.hiboos.com/refund/list", {
            "headers": {
                "accept": "application/json, text/plain, */*",
                "accept-language": "zh-CN,zh;q=0.9",
                "content-type": "application/x-www-form-urlencoded",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin"
            },
            "referrer": "https://zt.hiboos.com/index.html",
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": 'body={"yztStationNo":"","channelId":"","applyDeal":"","createTimeBegin":"' + $("createdate").value + '","createTimeEnd":"' + $("createdate").value + '","verificationStatus":"","tabType":"0","pageSize":100,"pageNo":1}',
            "method": "POST",
            "mode": "cors",
            "credentials": "include"
        }).then(res => res.json()).then(pobj => {
            try {
                hiboosxls = [];
                if (pobj.result.totalCount == 0) {
                    getover |= 2;
                    if (getover == 3) {
                        createtbody();
                    }
                    return true;
                }
                var templist = [];
                for (var i = 0; i < pobj.result.resultList.length; i++) {
                    if (pobj.result.resultList[i].refundWorkflowType != 10) {
                        templist[templist.length] = pobj.result.resultList[i].refundId;
                    }
                }
                if (templist.length == 0) {
                    getover |= 2;
                    if (getover == 3) {
                        createtbody();
                    }
                    return true;
                }
                var getwares = function (idrow) {
                    if (idrow >= templist.length) {
                        getover |= 2;
                        if (getover == 3) {
                            createtbody();
                        }
                        return true;
                    }
                    fetch("https://zt.hiboos.com/refund/detail", {
                        "headers": {
                            "accept": "application/json, text/plain, */*",
                            "accept-language": "zh-CN,zh;q=0.9",
                            "content-type": "application/x-www-form-urlencoded",
                            "sec-fetch-dest": "empty",
                            "sec-fetch-mode": "cors",
                            "sec-fetch-site": "same-origin"
                        },
                        "referrer": "https://zt.hiboos.com/index.html",
                        "referrerPolicy": "strict-origin-when-cross-origin",
                        "body": 'body={"refundId":"' + templist[idrow] + '","yztStationNo":"' + hiboosId + '"}',
                        "method": "POST",
                        "mode": "cors",
                        "credentials": "include"
                    }).then(res => res.json()).then(pobj => {
                        for (var i = 0; i < pobj.result.products.length; i++) {
                            var hiboosrow = [];
                            hiboosrow[0] = pobj.result.logs[pobj.result.logs.length - 1].operateTime;
                            hiboosrow[1] = pobj.result.orderId;
                            hiboosrow[2] = pobj.result.applyDealName;
                            hiboosrow[3] = pobj.result.products[i].skuName;
                            hiboosrow[4] = pobj.result.products[i].refundCount;
                            hiboosxls[hiboosxls.length] = hiboosrow;
                        }
                        getwares(idrow + 1);
                    });
                }
                getwares(0);
            } catch (err) {
                console.log(err.message);
            }
        });
    };
    $('htmlprint').addEventListener("click", function () {
        htmlorxls = 1
        $('createdate').setAttribute("disabled", "disabled");
        $('htmlprint').setAttribute("disabled", "disabled");
        $('xlsprint').setAttribute("disabled", "disabled");
        $('htmlprint').innerText = '读取中，请稍后……';
        getover = 0;
        getdmallxls();
        gethiboosxls();
    });
    // Your code here...
})();